<template>
  <div class="countdown">
    <div style="color: #999; margin-right: 10upx">还剩:</div>
    <div class="day">
      <span class="text">{{ d }}</span
      >天
    </div>
    <div class="time" style="margin-left: 9rpx">{{ h < 10 ? '0' + h : h }}</div>
    <span class="text">时</span>
    <div class="time">{{ m < 10 ? '0' + m : m }}</div>
    <span class="text">分</span>
    <div class="time" v-if="false">{{ s < 10 ? '0' + s : s }}</div>
    <!-- {{d}} {{h}} {{m}} -->
  </div>
</template>

<script>
export default {
  props: {
    startTime: {
      type: String,
    },
    endTime: {
      type: String,
    },
  },
  data() {
    return {
      timer: null,
      d: 0,
      h: 0,
      m: 0,
      s: 0,
      today: null,
    }
  },
  mounted() {
    this.time()
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },
  computed: {
    sTime() {
      return this.startTime
    },
    eTime() {
      return this.endTime
    },
  },
  watch: {
    endTime() {
      clearInterval(this.timer)
      this.time()
    },
  },
  methods: {
    time() {
      let leftTime = this.GetDateDiff(this.sTime, this.eTime)
      this.getCountdownTime(leftTime)
    },
    //计算两个时间差
    GetDateDiff(startTime, endTime) {
      var dateToday = new Date() //获取当前时间
      // this.today=new Date()
      //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
      startTime = startTime.replace(/\-/g, '/')
      endTime = endTime.replace(/\-/g, '/')
      //将计算间隔类性字符转换为小写
      var sTime = new Date(startTime)
      var eTime = new Date(endTime)
      // var dateDiff = eTime.getTime() - dateToday.getTime();//时间差的毫秒数
      // var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
      // console.log(dayDiff,33)

      return parseInt((eTime.getTime() - dateToday.getTime()) / 1000)
    },
    //计算活动结束时间
    getCountdownTime(leftTime) {
      let time = leftTime
      if (time > 0) {
        this.timer = setInterval(() => {
          if (time == 0) {
            clearInterval(this.timer)
            this.h = 0
            this.m = 0
            this.s = 0
          } else {
            this.d = parseInt(leftTime / 3600 / 24)
            this.h = parseInt((time / 3600) % 24)
            this.m = parseInt((time / 60) % 60)
            this.s = parseInt(time % 60)
            time--
          }
        }, 1000)
      }
    },
  },
}
</script>

<style lang="less" scoped>
.countdown {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #fff;
  .day {
    font-size: 14px;
    margin-right: 2px;
    color: #606060;
    display: flex;
    align-items: center;
    .text {
      color: #fd3c22;
      font-size: 16px;
      font-weight: bold;
    }
  }
  .time {
    padding: 1px 5px;
    background-color: #606060;
    border-radius: 2px;
    box-sizing: border-box;
  }
  .text {
    font-size: 12px;
    font-weight: bolder;
    margin: 0 6px;
    color: #606060;
  }
}
</style>
